import React, { useState } from 'react';
import styles from './index.less';
import {
  DatePicker,
  Space,
  Button,
  Input,
  Table,
  Form,
  Select,
  message,
  Modal,
  Row,
  Col,
  Spin,
} from 'antd';
import { Link } from 'react-router-dom';
import {
  getCollage,
  getTeacher,
  getClasses,
  getGrade,
  getMajor,
} from '@/pages/admin/pulic';
const { RangePicker } = DatePicker;
const { Option } = Select;
import { SAddEdit, UserEditObject } from './sAddEdit';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import qs from 'qs';

const { confirm } = Modal;

import request from '@/http';

export default () => {
  const [state, setState] = React.useState({
    selectedRowKeys: [], // Check here to configure the default column
    loading: false,
  });

  const [currentEditObject, setCurrentEditObject] =
    React.useState<UserEditObject>({
      isModalVisible: false,
      disAble: false,
    });

  const [formObject] = Form.useForm();
  const [dataSource, setDataSource] = React.useState<any[]>([]);
  const [loadingState, setLoadingState] = React.useState({ loading: true });
  const [pagination, setPagination] = React.useState({
    current: 1,
    total: 10,
    pageSize: 10,
    showSizeChanger: true,
    pageSizeOptions: ['5', '10', '50', '200', '500'],
    showQuickJumper: true,
  });

  const loadDataSource = async (
    userParams: any,
    pageValue: any,
    pageSize: any,
  ) => {
    var dataStr = '';
    const ds = {
      ...userParams,
      current: pageValue,
      size: pageSize,
    };
    console.log({ ...userParams });
    for (var n in ds) {
      if (dataStr != '') dataStr += '&';
      dataStr += encodeURIComponent(n) + '=' + encodeURIComponent(ds[n]);
    }

    const result: any = await request.post(
      '/api/admin/studentInfoManagement/getClassInfoPage',
      qs.stringify(ds),
    );
    console.log(result);

    if (result.code == 200) {
      console.log(1);

      const data = result.data.records.map((user: any) => ({
        key: `user_${user.id}`,
        id: user.id,
        collegesName: user.collegesName,
        collegesId: user.id,
        majorName: user.majorName,
        majorId: user.majorId,
        gradeName: user.gradeName,
        gradeInfoId: user.gradeInfoId,
        className: user.className,
        classBaseInfoId: user.classBaseInfoId,
        classTeacher: user.classTeacher,
        teacherId: user.teacherId,
        isGraduation: user.isGraduation,
        studentTotal: user.studentTotal,
      }));

      const newPageObject = {
        ...pagination,
        current: pageValue,
        pageSize: pageSize,
        total: result.data.total, //总条数 分页               *******************
      };
      console.log(result.data.total);
      setPagination(newPageObject);
      setDataSource(data);
      setLoadingState({ loading: false });
    }
  };

  //搜索框取值   localStorage存储
  let cCollege = localStorage.getItem('collegesName');
  if (cCollege != null) {
    var cCollegeData = JSON.parse(cCollege);
  }

  let cMajor = localStorage.getItem('major');
  if (cMajor != null) {
    var cMajorData = JSON.parse(cMajor);
  }

  const cGrade = localStorage.getItem('gradeName');
  if (cGrade != null) {
    var cGradeData = JSON.parse(cGrade);
  }
  let cClass = localStorage.getItem('classname');
  if (cClass != null) {
    var cClassData = JSON.parse(cClass);
  }

  const searchOnClick = async () => {
    setLoadingState({ loading: true });

    const data = formObject.getFieldsValue();
    console.log(data);
    let dataStr = '';
    let ds = {
      ...data,
    };

    await loadDataSource(ds, 1, pagination.pageSize);
  };

  React.useEffect(() => {
    getCollage();
    getMajor();
    getClasses();
    getGrade();
    getTeacher();
    loadDataSource(null, 1, pagination.pageSize).finally();
  }, []);

  /*const major = async () => {
    await getCollage();
    getMajor(formObject)
  }
*/

  const pageOnChange = async (page: any) => {
    await loadDataSource(
      formObject.getFieldsValue(),
      page.current,
      page.pageSize,
    );
  };

  async function userEditOnClose() {
    await loadDataSource(
      formObject.getFieldsValue(),
      pagination.current,
      pagination.pageSize,
    );
  }

  const disableOnClick = async (user: any) => {
    const result: any = await request.get(
      '/admin/disableTeacherById?id=' + user.id,
    );
    if (result.success) {
      message.success('操作成功！');
      await loadDataSource(
        formObject.getFieldsValue(),
        pagination.current,
        pagination.pageSize,
      );
    }
  };

  //重置按钮
  const resetOnClick = () => {
    formObject.resetFields();
  };

  return (
    <div className="pageMain">
      <div className="pageContent">
        <Row
          className="search"
          style={{
            minWidth: 1200,
            maxWidth: 1300,
            position: 'relative',
            display: 'inline-block',
          }}
        >
          <div className={styles.searchForm}>
            <Form layout="inline" form={formObject}>
              <Col span={8}>
                <Form.Item
                  label="院&nbsp;&nbsp;&nbsp;&nbsp;系"
                  name="collegesName"
                  initialValue=""
                >
                  <Select className="">
                    <Option value="">请选择...</Option>
                    {cCollegeData
                      ? cCollegeData.map((item: any, index: any) => {
                          return (
                            <Option
                              index={index}
                              key={index}
                              value={item.collegeName}
                              children={item.collegeName}
                            />
                          );
                        })
                      : ''}
                  </Select>
                </Form.Item>
              </Col>

              <Col span={8}>
                <Form.Item
                  label="专&nbsp;&nbsp;&nbsp;&nbsp;业"
                  name="majorName"
                  initialValue=""
                >
                  <Select className="">
                    <Option value="">请选择...</Option>
                    {cMajorData
                      ? cMajorData.map((item: any, index: any) => {
                          return (
                            <Option
                              index={index}
                              key={index}
                              value={item.majorName}
                              children={item.majorName}
                            />
                          );
                        })
                      : ''}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  label="年&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;级"
                  name="gradeName"
                  initialValue=""
                >
                  <Select>
                    <Option value="">请选择...</Option>
                    {cGradeData
                      ? cGradeData.map((item: any, index: any) => {
                          return (
                            <Option
                              index={index}
                              key={index}
                              value={item.gradeName}
                              children={item.gradeName}
                            />
                          );
                        })
                      : ''}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  label="班&nbsp;&nbsp;&nbsp;&nbsp;级"
                  name="className"
                  initialValue=""
                >
                  <Select className="">
                    <Option value="">请选择...</Option>
                    {cClassData
                      ? cClassData.map((item: any, index: any) => {
                          return (
                            <Option
                              index={index}
                              key={index}
                              value={item.className}
                              children={item.className}
                            />
                          );
                        })
                      : ''}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="班主任" name="classTeacher">
                  <Input className="" placeholder="请输入..." />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="是否结业" name="isGraduation" initialValue="">
                  <Select className="">
                    <Option value="">请选择...</Option>
                    <Option value="1">已结业</Option>
                    <Option value="0">未结业</Option>
                  </Select>
                </Form.Item>
              </Col>
            </Form>
          </div>
        </Row>

        <Button
          style={{
            display: 'inline-block',
            position: 'absolute',
            margin: '70px 0px 0px -30px ',
          }}
          type="primary"
          onClick={searchOnClick}
        >
          查询
        </Button>
        <Button
          style={{
            display: 'inline-block',
            position: 'absolute',
            margin: '70px 0px 0px 50px',
          }}
          onClick={resetOnClick}
        >
          重置
        </Button>

        <div className={styles.mainTable}>
          <Button
            style={{ marginBottom: '10px' }}
            type="primary"
            onClick={() => {
              setCurrentEditObject({
                isModalVisible: true,
                disAble: false,
              });
            }}
          >
            新增班级
          </Button>
          <Spin tip="Loading..." spinning={loadingState.loading}>
            <Table
              columns={[
                {
                  title: '院系',
                  dataIndex: 'collegesName',
                  key: 'collegesName',
                  width: 75,
                  align: 'center',
                },
                {
                  key: 'collegesId',
                  width: 0.001,
                  align: 'center',
                },
                {
                  title: '专业',
                  dataIndex: 'majorName',
                  key: 'majorName',
                  width: 100,
                  align: 'center',
                },
                {
                  key: 'majorId',
                  width: 0.001,
                  align: 'center',
                },
                {
                  title: '年级',
                  dataIndex: 'gradeName',
                  key: 'gradeName',
                  width: 75,
                  align: 'center',
                },
                {
                  key: 'gradeInfoId',
                  width: 0.001,
                  align: 'center',
                },
                {
                  title: '班级',
                  dataIndex: 'className',
                  key: 'className',
                  width: 75,
                  align: 'center',
                },
                {
                  key: 'classBaseInfoId',
                  width: 0.001,
                  align: 'center',
                },
                {
                  title: '班主任 ',
                  dataIndex: 'classTeacher',
                  key: 'classTeacher',
                  width: 75,
                  align: 'center',
                },
                {
                  key: 'teacherId',
                  width: 0.001,
                  align: 'center',
                },
                {
                  title: '是否结业',
                  dataIndex: 'isGraduation',
                  key: 'isGraduation',
                  width: 75,
                  render: (isGraduation) =>
                    isGraduation == '0' ? '未结业' : '已结业',
                  align: 'center',
                },
                {
                  title: '学员总数',
                  dataIndex: 'studentTotal',
                  key: 'studentTotal',
                  width: 75,
                  align: 'center',
                },

                {
                  title: '操作',
                  key: 'action',
                  align: 'center',
                  width: 75,
                  render: (row: any) => (
                    <>
                      <Link
                        to={{ pathname: 'studentDetail', state: { ...row } }}
                      >
                        <Button
                          type="link"
                          style={{ padding: '4px 8px' }}
                          onClick={() => {
                            window.localStorage.setItem('id', row.id);
                          }}
                        >
                          {' '}
                          学员明细
                        </Button>
                      </Link>
                      <Button
                        type="link"
                        onClick={() => {
                          // console.log(...row+ '00000000')
                          setCurrentEditObject({
                            ...row,
                            isModalVisible: true,
                            disAble: true,
                          });
                        }}
                        style={{ padding: '4px 8px' }}
                      >
                        编辑
                      </Button>
                    </>
                  ),
                },
              ]}
              dataSource={dataSource}
              pagination={pagination}
              onChange={pageOnChange}
              tableLayout="fixed"
              style={{ minWidth: 800 }}
            />
          </Spin>
          <SAddEdit editObject={currentEditObject} onClose={userEditOnClose} />
        </div>
      </div>
    </div>
  );
};
